import { useMemo, useState, useImperativeHandle, forwardRef } from 'react';
import { RightOutlined, LeftOutlined } from '@ant-design/icons';
import eventStart from '../../assets/images/eventStart.svg';
import eventEnd from '../../assets/images/eventEnd.svg';
import taskUser from '../../assets/images/taskUser.svg';
import taskCountersign from '../../assets/images/taskCountersign.svg';
// import taskExternal from '../../assets/images/taskExternal.svg';
import branckSerial from '../../assets/images/branckSerial.svg';
import branchParallel from '../../assets/images/branchParallel.svg';
import branchInclude from '../../assets/images/branchInclude.svg';
import processSub from '../../assets/images/processSub.svg';
import { uid } from '@inbiz/shared';
import './style.less';

let taskNumbers: any = {
    'bpmn:StartEventstart': 0,
    'bpmn:UserTasktask': 0,
    'bpmn:UserTaskctSign': 0,
    'bpmn:InclusiveGatewaygateway': 0,
    'bpmn:ParallelGatewaygateway': 0,
    'bpmn:ExclusiveGatewaygateway': 0,
    'bpmn:CallActivitytask': 0,
    'bpmn:EndEventend': 0,
};

const customPalette = forwardRef((props: any, ref) => {
    const { customModeler } = props;
    const [visiable, setVisiable] = useState(true);

    const _elements = useMemo(() => {
        return [
            {
                label: '开始',
                icon: eventStart,
                type: 'bpmn:StartEvent',
                idType: 'start',
                options: {
                    name: '开始',
                },
            },
            {
                label: '结束',
                icon: eventEnd,
                type: 'bpmn:EndEvent',
                idType: 'end',
                options: {
                    name: '结束',
                },
            },
            {
                label: '用户任务',
                icon: taskUser,
                type: 'bpmn:UserTask',
                idType: 'task',
                options: {
                    name: '用户任务',
                },
            },
            {
                label: '会签任务',
                icon: taskCountersign,
                type: 'bpmn:UserTask',
                idType: 'ctSign',
                options: {
                    name: '会签任务',
                },
            },
            {
                label: '串行分支',
                icon: branckSerial,
                type: 'bpmn:ExclusiveGateway',
                idType: 'gateway',
                options: {
                    name: '串行分支',
                },
            },
            {
                label: '并行分支',
                icon: branchParallel,
                type: 'bpmn:ParallelGateway',
                idType: 'gateway',
                options: {
                    name: '并行分支',
                },
            },
            {
                label: '包含分支',
                icon: branchInclude,
                type: 'bpmn:InclusiveGateway',
                idType: 'gateway',
                options: {
                    name: '包含分支',
                },
            },
            {
                label: '子流程',
                icon: processSub,
                idType: 'task',
                type: 'bpmn:CallActivity',
                options: {
                    name: '子流程',
                },
            },
        ]
    }, []);

    const getElementHeight = (type: string) => {
        switch (type) {
            case 'bpmn:StartEvent':
            case 'bpmn:EndEvent':
                return 30;
            case 'bpmn:UserTask':
            case 'bpmn:CallActivity':
                return 60;
            case 'bpmn:ExclusiveGateway':
            case 'bpmn:ParallelGateway':
            case 'bpmn:InclusiveGateway':
                return 50;
            default:
                return 60;
        }
    };

    const getElementWidth = (type: string) => {
        switch (type) {
            case 'bpmn:StartEvent':
            case 'bpmn:EndEvent':
                return 30;
            case 'bpmn:UserTask':
            case 'bpmn:CallActivity':
                return 100;
            case 'bpmn:ExclusiveGateway':
            case 'bpmn:ParallelGateway':
            case 'bpmn:InclusiveGateway':
                return 50;
            default:
                return 100;
        }
    }

    const _createElement = (event: any, element: any) => {
        if (element?.type == 'bpmn:StartEvent' || !customModeler) {
            return;
        };
        const ElementRegistry = customModeler.get('elementRegistry');
        const allElements = ElementRegistry.getAll();
        if (element?.type == 'bpmn:EndEvent' && allElements?.some((item: { type: string; }) => item?.type == 'bpmn:EndEvent')) {
            return;
        };
        let _selectedElements = customModeler.get('selection')._selectedElements;
        _selectedElements.forEach((item: any) => {
            customModeler.get('selection').deselect(item);
        });
        const ElementFactory = customModeler.get('elementFactory');
        const BpmnFactory = customModeler.get('bpmnFactory');
        const create = customModeler.get('create');
        let type = element?.type;
        const taskBusinessObject = BpmnFactory.create(type, {
            id: element?.idType + '-' + uid(32).toUpperCase(),
            ...element?.options,
            name: element?.type == 'bpmn:EndEvent' ? element?.options?.name : element?.options?.name + ++taskNumbers[element?.type + element?.idType],
        });
        const shape = ElementFactory.createShape(Object.assign({ type: type, businessObject: taskBusinessObject, }, { height: getElementHeight(type), width: getElementWidth(type) }));
        create.start(event, shape);
    };

    useImperativeHandle(ref, () => ({
        paletteVisiable: visiable,
    }));

    return (
        <div className="bpmn-custom-palette-wrapper" style={{ width: visiable ? 130 : 0 }}>
            <div className="bpmn-custom-palette-content" style={{ left: visiable ? 0 : -130, opacity: visiable ? 1 : 0 }}>
                <div className='bpmn-custom-palette-title'>流程节点</div>
                {
                    _elements?.map((item: { label: string, icon: any, options: any, type: string }) => {
                        let _draggable = true;
                        if (item?.type == 'bpmn:StartEvent') {
                            _draggable = false;
                        };
                        let allElements: any[] = [];
                        if (customModeler) {
                            const ElementRegistry = customModeler.get('elementRegistry');
                            allElements = ElementRegistry.getAll();
                        };
                        if (item?.type == 'bpmn:EndEvent' && allElements?.some((item: { type: string; }) => item?.type == 'bpmn:EndEvent')) {
                            _draggable = false;
                        };
                        if (!customModeler) {
                            _draggable = false;
                        };
                        return (
                            <div
                                className='bpmn-custom-palette-element'
                                key={item.label}
                                draggable={_draggable}
                                onDragStart={(event: any) => { _createElement(event, item); }}
                                title={item.label}
                            >
                                <div className='bpmn-custom-palette-element-icon'><img src={item.icon} /></div>
                                <div className='bpmn-custom-palette-element-label'>{item.label}</div>
                            </div>
                        )
                    })
                }
            </div>
            <div className='bpmn-custom-palette-icon' onClick={() => { setVisiable(!visiable) }}>
                {
                    visiable
                        ?
                        <LeftOutlined />
                        :
                        <RightOutlined />
                }

            </div>
        </div>
    )
})

export default customPalette